




function sendstart(){
    lastpic = "";
}
sendstart();


console.log(" get 1688 ok ");
var lastpic;
var charCount = {};
chrome.runtime.onMessage.addListener(async (msg, sender) => {
  console.log(" get 1688 msg ok ")
  for(var i=0;i<msg['data']['list'].length;i++){
         pic_url = msg['data']['list'][i]['pic_url'];
         q = msg['data']['list'][i]['q'];
         var priceStart = msg['data']['list'][i]['priceStart'];
         var priceEnd = msg['data']['list'][i]['priceEnd'];
         var amazon_id = msg['data']['list'][i]['amazon_id'];
           console.log(pic_url);
           //console.log("same pic_"+lastpic+"_"+pic_url);
            if(lastpic == pic_url){
                if(!charCount[pic_url]){
                    charCount[pic_url] = 1;
                }else{
                    charCount[pic_url]++;
                }
                console.log("same pic_"+lastpic+"_time"+charCount[pic_url]);
                if(charCount[pic_url] <= 10){
                    continue;
                }else{
                    delete charCount[pic_url];
                    lastpic = "";
                    continue;
                }
            }else{
                charCount={};
            }
            lastpic = pic_url;
           fetchAndCompressImage(pic_url, 600, 600)
          .then((base64) => {
            //console.log(base64);

              var cookieTk =  getCookie("_m_h5_tk");
              var milliseconds = new Date().valueOf();;
              //milliseconds = "1685531692825";
              const cookieTkList = cookieTk.split('_');
                var data={};
                const commaIndex = base64.indexOf(',');
                data.imageBase64 =  base64.substring(commaIndex + 1);;
                 data.appName = "searchImageUpload";
                 data.appKey = "pvvljh1grxcmaay2vgpe9nb68gg9ueg2";
                 var dataString = JSON.stringify(data);
                 mms = cookieTkList[0]+"&"+milliseconds+"&12574478&"+dataString;
                 //console.log(" mms: "+ mms)
                 var sign = hhh(mms)
                 console.log(" sign: "+ sign)
                $.ajax({
                    url: 'https://h5api.m.1688.com/h5/mtop.1688.imageservice.putimage/1.0/?jsv=2.7.0&appKey=12574478&t='+milliseconds+'&sign='+sign+'&api=mtop.1688.imageService.putImage&ecode=0&v=1.0&type=originaljson&dataType=jsonp',
            　　　　 type: 'POST',
                    data:{data:dataString},
                    xhrFields: {
                        withCredentials: true // 这里设置了withCredentials
                    },
                    success: function(data) {

                        var img_id_1688 = data.data.imageId
                        //console.log(data);
                         $.ajax({
                            url: 'https://search.1688.com/service/imageSearchOfferResultViewService?priceStart='+priceStart+'&priceEnd='+priceEnd+'&tab=imageSearch&imageAddress=&spm=a26352.b28411319.searchbox.input&extendProperties=buyerProtection:essxsfh,buyerProtection:ssbxsfh&beginPage=1&pageSize=10&pageName=image&imageId='+img_id_1688,//+"&imageKeywords="+q
                    　　　　 type: 'GET',
                            xhrFields: {
                                withCredentials: true // 这里设置了withCredentials
                            },
                            success: function(data) {
                                //console.log(data);
                                var type="data1688amazon";
                                var body = data;
                                console.log(" send data1688amazon amazon_id:"+amazon_id);
                                chrome.runtime.sendMessage({ data: {type, amazon_id , body }, close: false });
                            },
                            error: function(err) {
                                console.error(err)
                                sendstart();
                            }
                        });


                    },
                    error: function(err) {
                        console.error(err)
                        sendstart();
                    }
                });

          })
          .catch((err) => {
            console.log('Error:', err);
            sendstart();
          });

           /*var xhr = new XMLHttpRequest();
           fetch(pic_url, {
                responseType: 'blob'
           })
            .then(response => {
                return response.blob();
            })
            .then(blob => {
                let oFileReader = new FileReader();
                oFileReader.onloadend = function(e) {
                     const pic_base64 = e.target.result.substr(23);
                  var cookieTk =  getCookie("_m_h5_tk");
                  var milliseconds = new Date().valueOf();;
                  //milliseconds = "1685531692825";
                  const cookieTkList = cookieTk.split('_');
                    var data={};
                     data.imageBase64 = pic_base64;
                     data.appName = "searchImageUpload";
                     data.appKey = "pvvljh1grxcmaay2vgpe9nb68gg9ueg2";
                     var dataString = JSON.stringify(data);
                     mms = cookieTkList[0]+"&"+milliseconds+"&12574478&"+dataString;
                     //console.log(" mms: "+ mms)
                     var sign = hhh(mms)
                     console.log(" sign: "+ sign)
                    $.ajax({
                        url: 'https://h5api.m.1688.com/h5/mtop.1688.imageservice.putimage/1.0/?jsv=2.7.0&appKey=12574478&t='+milliseconds+'&sign='+sign+'&api=mtop.1688.imageService.putImage&ecode=0&v=1.0&type=originaljson&dataType=jsonp',
                　　　　 type: 'POST',
                        data:{data:dataString},
                        xhrFields: {
                            withCredentials: true // 这里设置了withCredentials
                        },
                        success: function(data) {

                            var img_id_1688 = data.data.imageId
                            console.log(data);
                             $.ajax({
                                url: 'https://search.1688.com/service/imageSearchOfferResultViewService?tab=imageSearch&imageAddress=&spm=a26352.b28411319.searchbox.input&tags=4360897&beginPage=1&pageSize=10&pageName=image&imageId='+img_id_1688,
                        　　　　 type: 'GET',
                                xhrFields: {
                                    withCredentials: true // 这里设置了withCredentials
                                },
                                success: function(data) {
                                    console.log(data);
                                    var type="data1688";
                                    var body = data;
                                    chrome.runtime.sendMessage({ data: {type, pic_url , body }, close: false })
                                },
                                error: function(err) {
                                    console.error(err)
                                }
                            });


                        },
                        error: function(err) {
                            console.error(err)
                        }
                    });
                };
             oFileReader.readAsDataURL(blob);

        });*/




  }
})


/*
var image = new Image();
image.src = img;
image.onload = function(){
  var base64 = getBase64Image(image);
  console.log(base64);
}*/


/*
$(document).mousemove(function(event){
    console.log(event.pageX + ", " + event.pageY)
});*/






function hhh(e) {
	function t(e, t) {
		return e << t | e >>> 32 - t
	}

	function n(e, t) {
		var n, o, r, i, a;
		return r = 2147483648 & e, i = 2147483648 & t, a = (1073741823 & e) + (1073741823 & t), (n = 1073741824 & e) & (o = 1073741824 & t) ? 2147483648 ^ a ^ r ^ i : n | o ? 1073741824 & a ? 3221225472 ^ a ^ r ^ i : 1073741824 ^ a ^ r ^ i : a ^ r ^ i
	}

	function o(e, o, r, i, a, s, p) {
		return e = n(e, n(n(function(e, t, n) {
			return e & t | ~e & n
		}(o, r, i), a), p)), n(t(e, s), o)
	}

	function r(e, o, r, i, a, s, p) {
		return e = n(e, n(n(function(e, t, n) {
			return e & n | t & ~n
		}(o, r, i), a), p)), n(t(e, s), o)
	}

	function i(e, o, r, i, a, s, p) {
		return e = n(e, n(n(function(e, t, n) {
			return e ^ t ^ n
		}(o, r, i), a), p)), n(t(e, s), o)
	}

	function a(e, o, r, i, a, s, p) {
		return e = n(e, n(n(function(e, t, n) {
			return t ^ (e | ~n)
		}(o, r, i), a), p)), n(t(e, s), o)
	}

	function s(e) {
		var t, n = '',
			o = '';
		for (t = 0; t <= 3; t++) n += (o = '0' + (e >>> 8 * t & 255)
				.toString(16))
			.substr(o.length - 2, 2);
		return n
	}
	var p, u, c, d, l, f, m, g, h, v;
	for (p = function(e) {
		for (var t, n = e.length, o = n + 8, r = 16 * ((o - o % 64) / 64 + 1), i = new Array(r - 1), a = 0, s = 0; s < n;) a = s % 4 * 8, i[t = (s - s % 4) / 4] = i[t] | e.charCodeAt(s) << a, s++;
		return i[t = (s - s % 4) / 4] = i[t] | 128 << (a = s % 4 * 8), i[r - 2] = n << 3, i[r - 1] = n >>> 29, i
	}(e = function(e) {
		e = e.replace(/\r\n/g, '\n');
		for (var t = '', n = 0; n < e.length; n++) {
			var o = e.charCodeAt(n);
			o < 128 ? t += String.fromCharCode(o) : o > 127 && o < 2048 ? (t += String.fromCharCode(o >> 6 | 192), t += String.fromCharCode(63 & o | 128)) : (t += String.fromCharCode(o >> 12 | 224), t += String.fromCharCode(o >> 6 & 63 | 128), t += String.fromCharCode(63 & o | 128))
		}
		return t
	}(e)), m = 1732584193, g = 4023233417, h = 2562383102, v = 271733878, u = 0; u < p.length; u += 16) c = m, d = g, l = h, f = v, m = o(m, g, h, v, p[u + 0], 7, 3614090360), v = o(v, m, g, h, p[u + 1], 12, 3905402710), h = o(h, v, m, g, p[u + 2], 17, 606105819), g = o(g, h, v, m, p[u + 3], 22, 3250441966), m = o(m, g, h, v, p[u + 4], 7, 4118548399), v = o(v, m, g, h, p[u + 5], 12, 1200080426), h = o(h, v, m, g, p[u + 6], 17, 2821735955), g = o(g, h, v, m, p[u + 7], 22, 4249261313), m = o(m, g, h, v, p[u + 8], 7, 1770035416), v = o(v, m, g, h, p[u + 9], 12, 2336552879), h = o(h, v, m, g, p[u + 10], 17, 4294925233), g = o(g, h, v, m, p[u + 11], 22, 2304563134), m = o(m, g, h, v, p[u + 12], 7, 1804603682), v = o(v, m, g, h, p[u + 13], 12, 4254626195), h = o(h, v, m, g, p[u + 14], 17, 2792965006), m = r(m, g = o(g, h, v, m, p[u + 15], 22, 1236535329), h, v, p[u + 1], 5, 4129170786), v = r(v, m, g, h, p[u + 6], 9, 3225465664), h = r(h, v, m, g, p[u + 11], 14, 643717713), g = r(g, h, v, m, p[u + 0], 20, 3921069994), m = r(m, g, h, v, p[u + 5], 5, 3593408605), v = r(v, m, g, h, p[u + 10], 9, 38016083), h = r(h, v, m, g, p[u + 15], 14, 3634488961), g = r(g, h, v, m, p[u + 4], 20, 3889429448), m = r(m, g, h, v, p[u + 9], 5, 568446438), v = r(v, m, g, h, p[u + 14], 9, 3275163606), h = r(h, v, m, g, p[u + 3], 14, 4107603335), g = r(g, h, v, m, p[u + 8], 20, 1163531501), m = r(m, g, h, v, p[u + 13], 5, 2850285829), v = r(v, m, g, h, p[u + 2], 9, 4243563512), h = r(h, v, m, g, p[u + 7], 14, 1735328473), m = i(m, g = r(g, h, v, m, p[u + 12], 20, 2368359562), h, v, p[u + 5], 4, 4294588738), v = i(v, m, g, h, p[u + 8], 11, 2272392833), h = i(h, v, m, g, p[u + 11], 16, 1839030562), g = i(g, h, v, m, p[u + 14], 23, 4259657740), m = i(m, g, h, v, p[u + 1], 4, 2763975236), v = i(v, m, g, h, p[u + 4], 11, 1272893353), h = i(h, v, m, g, p[u + 7], 16, 4139469664), g = i(g, h, v, m, p[u + 10], 23, 3200236656), m = i(m, g, h, v, p[u + 13], 4, 681279174), v = i(v, m, g, h, p[u + 0], 11, 3936430074), h = i(h, v, m, g, p[u + 3], 16, 3572445317), g = i(g, h, v, m, p[u + 6], 23, 76029189), m = i(m, g, h, v, p[u + 9], 4, 3654602809), v = i(v, m, g, h, p[u + 12], 11, 3873151461), h = i(h, v, m, g, p[u + 15], 16, 530742520), m = a(m, g = i(g, h, v, m, p[u + 2], 23, 3299628645), h, v, p[u + 0], 6, 4096336452), v = a(v, m, g, h, p[u + 7], 10, 1126891415), h = a(h, v, m, g, p[u + 14], 15, 2878612391), g = a(g, h, v, m, p[u + 5], 21, 4237533241), m = a(m, g, h, v, p[u + 12], 6, 1700485571), v = a(v, m, g, h, p[u + 3], 10, 2399980690), h = a(h, v, m, g, p[u + 10], 15, 4293915773), g = a(g, h, v, m, p[u + 1], 21, 2240044497), m = a(m, g, h, v, p[u + 8], 6, 1873313359), v = a(v, m, g, h, p[u + 15], 10, 4264355552), h = a(h, v, m, g, p[u + 6], 15, 2734768916), g = a(g, h, v, m, p[u + 13], 21, 1309151649), m = a(m, g, h, v, p[u + 4], 6, 4149444226), v = a(v, m, g, h, p[u + 11], 10, 3174756917), h = a(h, v, m, g, p[u + 2], 15, 718787259), g = a(g, h, v, m, p[u + 9], 21, 3951481745), m = n(m, c), g = n(g, d), h = n(h, l), v = n(v, f);
	return (s(m) + s(g) + s(h) + s(v))
		.toLowerCase()
}; // 测试


//mms = o.token + '&' + s + '&' + a + '&' + n.data

function getCookie(cookieName) {
  const strCookie = document.cookie
  const cookieList = strCookie.split(';')

  for(let i = 0; i < cookieList.length; i++) {
    const arr = cookieList[i].split('=')
    if (cookieName === arr[0].trim()) {
      return arr[1]
    }
  }
  return ''
}


/**
 * 使用 fetch 获取远程图片资源并进行压缩裁剪和转换为 Base64 编码后，返回 promise 对象
 * @param {string} url - 远程图片资源 URL
 * @param {number} maxWidth - 图片最大宽度
 * @param {number} maxHeight - 图片最大高度
 * @returns {Promise} - 返回 Promise 对象，resolve 后为 Base64 编码的图片
 */
function fetchAndCompressImage(url, maxWidth, maxHeight) {
  return fetch(url)
    .then(response => response.blob())
    .then(blob => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => {
          const image = new Image();
          image.src = reader.result;
          image.crossOrigin = "anonymous";
          image.onload = () => {
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext('2d');
            const originalWidth = image.width;
            const originalHeight = image.height;
            // 获取图片最新的宽高
            const { width, height } = getNewSize(originalWidth, originalHeight, maxWidth, maxHeight);
            // 设置 canvas 宽高
            canvas.width = width;
            canvas.height = height;
            // 绘制图片
            ctx.drawImage(image, 0, 0, width, height);
            // 将 base64 作为 promise 返回
            resolve(canvas.toDataURL('image/jpeg'));
          };
          image.onerror = () => {
            reject(new Error('图片加载失败'));
          };
        }
        reader.readAsDataURL(blob);
      });
    })
    .catch(err => {
      console.log('fetch 错误：', err);
    });
}

/**
 * 获取图片最新的宽高
 */
function getNewSize(originalWidth, originalHeight, maxWidth, maxHeight) {
  // 如果图片宽高都小于限定值，则不进行裁剪和压缩
  if (originalWidth < maxWidth && originalHeight < maxHeight) {
    return {
      width: originalWidth,
      height: originalHeight,
    };
  }
  // 计算比例
  const ratio = Math.min(maxWidth / originalWidth, maxHeight / originalHeight);
  return {
    width: originalWidth * ratio,
    height: originalHeight * ratio,
  };
}